package com.palfund.tablayoutviewpagerfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;

/**
 * Created by clvc on 2017/7/27.
 * 真正的速度是看不见的 !
 * Today is today , we will go !
 * <p>
 * 避免ViewPger的预加载导致打开慢
 */

public abstract class LazyLoadFragment extends Fragment {
    // View是否创建
    protected boolean viewInitiated;
    // 用户是否可见
    protected boolean visibleToUser;
    protected boolean firsted = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewInitiated = true;
        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.visibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    /**
     * 获取数据
     */
    public abstract void fetchData();

    public boolean prepareFetchData() {
        if (visibleToUser && viewInitiated) {
            if (firsted) {
                fetchData();
                firsted = false;
            }
            return true;
        }
        return false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewInitiated = false;
    }
}